package com.redhat.auth.log.parse;


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import com.redhat.auth.log.common.ValueBean;
import com.redhat.auth.log.exception.LogException;

/**
 * 将前后的查询语句解析成一个DetachedCriteria
 * @author lingen.liu
 *
 */
public class CriteriaParse {
	
	/**
	 * 解析产生一个SQL
	 * @param entity
	 * @param keyValues
	 * @return
	 */
	public static List<String> parseSQL(ValueBean valueBean,HashMap<String,Object> keyValues){
		
		Set<String> keySet = keyValues.keySet();
		//对keyValues进行检测，如果是List，则构造多个DetachedCriteria,否则，则构造一个
		//允许配置以下情况
		/*
		 * 1 参数都是单值，没有List的存在
		 * 2 参数都是List，且个数相等
		 * 3 有的参数是List,有的为单值，为List的参数的值的个数相等
		 */
		int listCount = 1;
		Collection values = keyValues.values();
		for(Object value:values){
			if(value instanceof List){
				List listValue = (List)value;
				if(listCount != 1 && listCount!=listValue.size())throw new LogException("list config value error");
				listCount = listValue.size();
			}
		}
		
		List<String> sqls= new ArrayList<String>();
		for(int i=0;i<listCount;i++){
			
			String sql = "from "+valueBean.getEntity().getSimpleName()+" where ";
			int m = 0;
			for(String key:keySet){
				  sql = sql + key + "=" + keyValues.get(key).toString();
				  m++;
				  if(m!=keySet.size())sql = sql + "and";
			}
			sqls.add(sql);
			/*
			DetachedCriteria criteria =  DetachedCriteria.forClass(valueBean.getEntity()); 
			for(String key:keySet){
				criteria.add(Restrictions.eq(key,getKeyValue(key,keyValues,i)));
			}
			
			// 加入级联关系的处理
		
			 * 暂时不处理级联关系
			List<String> relations = valueBean.getCascadeProperties();
			for(String relation:relations){
				if(relation.trim().equals(""))continue;
				criteria.setFetchMode(relation.substring(0,relation.indexOf("[")), FetchMode.JOIN);
			}
			//去除由于关联查询带到的重复数据影响
			criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
			criterias.add(criteria);
			*/
			
		}
		return sqls;
	}
	
	
	private static Object getKeyValue(String key,HashMap<String,Object> keyValues,int i){
		Object value = keyValues.get(key);
		if(value instanceof List){
			List listValue =  (List)value;
			return listValue.get(i);
		}else{
			return value;
		}
	}
}
